import 'dart:developer';
import 'package:flutter_qiyu/flutter_qiyu.dart';
import 'package:get/get.dart';
import 'package:logger/logger.dart';
import 'package:sports_new/controller/service/resource_service.dart';
import 'package:sports_new/server/http/request_header.dart';
import 'package:sports_new/utils/constant.dart';
import 'package:sports_new/utils/user.dart';
import 'package:sports_new/utils/utils.dart';

import '../view/my/discount/tip_resources.dart';

extension StringEx2 on String {
  String get https => startsWith("http://") ? replaceFirst("http://", "https://") : this;
}

class OnlineContact {
  OnlineContact._internal();
  factory OnlineContact() => _instance;
  static final OnlineContact _instance = OnlineContact._internal();

  static const appKey = Constant.qiYuAppKey;

  String? _lastUserId;
  bool _isLogin = false;
  int _unreadCount = 0;
  bool _uinfobusy = false;
  // bool _inChatWindow = false;

  bool get isLogin => _isLogin;
  int get unreadCount => _unreadCount;
  String? get lastUserId => _lastUserId;
  bool inChatWindow = false;

  void Function()? onUnreadChange;

  unreadCountChange(int count) {
    if (_unreadCount == count) { return; }
    _unreadCount = count;
    onUnreadChange?.call();
  }

  init() async {
    final b = await QiYu.registerApp(appKey: appKey,appName: "qxb_kefu");
    log("qiyu regist $b");
    QiYu.registerListener(unreadCountChange);
    var online = Get.find<ResourceService>().contact?.where((element) => element.button == "qiyu").toList();
    if(online.hasValue){
      try {
        QiYu.setCustomUIConfig({"serviceHeadImage": online?.first.imgUrl});
      }catch(e){
        Logger().d(e);
      }
    }
  }

  setUserinfo() async {
    final userid = User.auth?.userId;
    log("set user info $userid $_lastUserId $_isLogin $_uinfobusy");
    if (_isLogin) {
      if (_lastUserId == userid) { return; }
    }
    if (_uinfobusy) { return; }
    _uinfobusy = true;
    try {
      final cond1 = (!_isLogin && _lastUserId == null);
      final cond2 = _isLogin;
      if ( cond1 || cond2) {
        QiYu.logout(); 
        QiYu.cleanCache();
        await Future.delayed(const Duration(milliseconds: 100));
        log("set user logout $userid $_lastUserId $_isLogin $_uinfobusy");
      }
      final data = '''
            [{"key":"real_name", "value":"${User.info?.name}"},
            {"key":"mobile_phone", "hidden":true, "value":"${User.info?.phone}"},
            {"key":"email", "value":""},
            {"index":0, "key":"uuid", "label":"uuid", "value":"${RequestHeader.uuid}", "href":""},
            {"index":1, "key":"account", "label":"账号", "value":"${User.auth?.userId}", "href":""},
            {"index":2, "key":"model", "label":"手机", "value":"${RequestHeader.model}"},
            {"index":5, "key":"reg_date", "label":"注册日期", "value":""},
            {"index":6, "key":"last_login", "label":"上次登录时间", "value":""}]
            ''';
      QYUserInfoParams userInfoParams = QYUserInfoParams.fromJson({
        'userId': '$userid',
        'data':data
      });
      _isLogin = await QiYu.setUserInfo(userInfoParams);
      await QiYu.setCustomUIConfig({"customerHeadImage": (User.info?.avatar ?? "").https});
      log("QiYu set avaer = ${User.info?.avatar}");
      if (_isLogin) { _lastUserId = userid; }
      log("set user after $userid $_lastUserId $_isLogin");
    } catch (err) {
      log("set user info err $err");
    }
    _uinfobusy = false;
  }

  openServiceWindow() async {
    await setUserinfo();
    QYServiceWindowParams serviceWindowParams =
    QYServiceWindowParams.fromJson({
      'source': {
        'sourceTitle': '',
        'sourceUrl': '',
        'sourceCustomInfo': ''
      },
      'sessionTitle': '球客岛客服',
      'groupId': 0,
      'staffId': 0,
      'robotId': 0,
      'robotFirst': false,
      'faqTemplateId': 0,
      'vipLevel': 0,
      'showQuitQueue': true,
      'showCloseSessionEntry': true
    });
    
    await QiYu.openServiceWindow(serviceWindowParams);
  }


}